package MTT::Controller::Users;
use Moose;
use namespace::autoclean;

BEGIN {extends 'Catalyst::Controller'; }

=head1 NAME

MTT::Controller::Users - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

use Data::Dumper;

use MTT::Form::Register;
use MTT::Form::Profile;

#use utf8;

sub base :Chained('/') :PathPart('users') :CaptureArgs(0) {
    my ( $self, $c ) = @_;
}

sub register :Chained('base') :PathPart('register') :Args(0) {
	my ($self, $c) = @_;

	if ( $c->check_user_roles('admin') ) {
		my $form = MTT::Form::Register->new();
		$c->stash(
			template => 'register.tt2',
			form => $form
		);

		if ( $c->req->method eq 'POST' ) {
			my $user = $c->model('DBIC::User')->new_result({});
			return unless $form->process( item => $user, params => $c->req->params );

			if ( $user->id ) {
				$user->create_related('user_roles', {role_id => $c->req->param('role')});
			}
			
			$c->flash(message => "Зарегистрирован новый пользователь: ${\( $user->username )}");
			$c->detach('/users/list');
		}
	}
	else {
		$c->response->body('Access denied');
	}
}

sub profile :Chained('base') :PathPart('id') :Args(1) {
	my ($self, $c, $id) = @_;

	unless ( $c->check_user_roles('admin') || $c->user->id eq $id ) {
		$c->response->body('Access denied for change');
	}

	my $form = MTT::Form::Profile->new( 
		item_id => $id,
		schema  => $c->model('DBIC')->schema
	);
	
	$c->stash(
		template => 'profile.tt2',
#		user => $c->user,
		form => $form
	);

	if ( $c->req->method eq 'POST' ) {
		my $user = $c->model('DBIC::User')->find($id);

		return unless $form->process( item => $user, params => $c->req->params );

		$c->flash(message => 'Изменения сохранены');
#		$c->response->redirect( $c->uri_for('/users/list') );
		if ( $c->check_user_roles('admin') ) {
			$c->detach('/users/list');
			return;
		}
	}

}

sub list :Chained('base') :PathPart('list') :Args(0) {
	my ($self, $c) = @_;

	if ( $c->check_user_roles('admin') ) {
		$c->stash(
			template => 'userlist.tt2',
			users => [ $c->model('DBIC::User')->all() ]
		);
	}
	else {
		$c->response->body('Access denied');
	}
}


sub access :Chained('base') :PathPart('access') :Args(1) {
	my ($self, $c, $id) = @_;
	$c->detach('Access', 'set_permission', [ $id ]);
}

=head1 AUTHOR

A clever guy

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
